import 'package:flutter/material.dart';
import 'package:english_words/english_words.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '爱的配对',
      theme: ThemeData(
        primarySwatch: Colors.purple,
      ),
      home: const MyHomePage(title: '配对列表'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final _words = <WordPair>[];
  final _myWords = <WordPair>[];

  @override
  Widget build(BuildContext context) {
    _words.addAll(generateWordPairs().take(10));
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        actions: [
          IconButton(onPressed: _showLoved, icon: const Icon(Icons.list))
        ],
      ),
      body: Center(
        child: _buildList(),
      ),
    );
  }

  Widget _buildList() {
    return ListView.builder(itemBuilder: (context, item) {
      if (item.isOdd) return const Divider();

      var index = item ~/ 2;

      if (index >= _words.length) _words.addAll(generateWordPairs().take(10));

      WordPair wp = _words[index];
      return _buildRow(wp);
    });
  }

  Widget _buildRow(WordPair wp) {
    return ListTile(
      title: Text(wp.asCamelCase),
      trailing: _buildLoveIcon(wp),
      onTap: () => {_loveWp(wp)},
    );
  }

  Widget _buildLoveIcon(WordPair wp) {
    bool _saved = _myWords.contains(wp);

    return Icon(
      _saved ? Icons.favorite : Icons.favorite_border,
      color: _saved ? Colors.red : null,
    );
  }

  void _loveWp(WordPair wp) {
    setState(() {
      if (_myWords.contains(wp)) {
        _myWords.remove(wp);
      } else {
        _myWords.add(wp);
      }
    });
  }

  void _showLoved() {
    Navigator.of(context)
        .push(MaterialPageRoute(builder: (BuildContext context) {
      final Iterable<ListTile> tiles = _myWords.map((wp) {
        return ListTile(
          title: Text(
            wp.asCamelCase,
            style: const TextStyle(fontSize: 16.0),
          ),
        );
      });
      final List<Widget> divided =
          ListTile.divideTiles(tiles: tiles, context: context).toList();

      return Scaffold(
        appBar: AppBar(
          title: const Text('麦叔喜欢的'),
        ),
        body: ListView(children: divided),
      );
    }));
  }
}
